const redis = require("redis"), rc = {rPORT:6379, rIP:"127.0.0.1"};
var clientList = [];

function openRedis(ind) {
    if (clientList[ind]) clientList[ind].end();
    clientList[ind] = redis.createClient(rc.rPORT, rc.rIP, { retry_strategy: 10000, enable_offline_queue: false });

    clientList[ind].on("connect", function() {
        LOG.error("redis connect", ind);
    });
    clientList[ind].on("ready", function() {
        if (ind > 0) clientList[ind].SELECT(ind);
    });

    clientList[ind].on("error", function(err) {
        LOG.error("redis error ", ind, err);
    });
    clientList[ind].on("end", function() {
        LOG.error("redis end", ind);
        setTimeout(function() { openRedis(ind) }, 3000);
    });
}

//订阅任务相关
function subscribeRedis(ind) {
    if (clientList[ind]) clientList[ind].end();
    clientList[ind] = redis.createClient(rc.rPORT, rc.rIP, { retry_strategy: 10000, enable_offline_queue: false });

    clientList[ind].on("message", function(channel, message) {
        var content = message.split(";");
        if (channel == "kickPlayerOut") {
            var fun = require("./module/pubFun.js");
            var jsong = { m: 23, s: 300, d: { wMessageType: 4, wExtType: 1, szContent: content[1] } };
            var d = { index: 0xFFFFFFFF, userid: content[0], serverid: 31, channelid: 0 };
            if (global.client) {
                for (var i = 0; i < global.client.length; i++) {
                    if (parseInt(content[1]) == 31) {
                        fun.writeData(global.client[i], d, null); //断线
                    } else {
                        fun.writeData(global.client[i], d, jsong); //通知
                    }
                }
            }
        }
    });

    clientList[ind].on("connect", function() {
        LOG.error("redis connect", ind);
    });
    clientList[ind].on("ready", function() {
        if (ind > 0) clientList[ind].SELECT(ind);
        clientList[ind].subscribe("kickPlayerOut");
    });
    clientList[ind].on("error", function(err) {
        LOG.error("redis error ", ind, err);
    });
    clientList[ind].on("end", function() {
        LOG.error("redis end", ind);
        setTimeout(function() { openRedis(ind) }, 3000);
    });
}

openRedis(0);
openRedis(1);
subscribeRedis(2);

//setTimeout(function(){console.log("end");client.end(true);}, 10000);


module.exports = function(index) {
    if (index > 0)
        return clientList[index];
    else
        return clientList[0];
}